package com.tqz.juc.aqs;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author tianqingzhao
 * @since 2023-06-04 18:53
 */
public class ConditionTest {

    public static void main(String[] args) {
        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();

        new Thread(new ConditionSignal(lock, condition)).start();
        new Thread(new ConditionAwait(lock, condition)).start();
    }

    private static class ConditionAwait implements Runnable {

        private final Lock lock;

        private final Condition condition;

        public ConditionAwait(Lock lock, Condition condition) {
            this.lock = lock;
            this.condition = condition;
        }

        @Override
        public void run() {
            lock.lock();
            try {
                System.out.println("begin condition await");
                condition.await();
                System.out.println("end condition await");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

    private static class ConditionSignal implements Runnable {

        private final Lock lock;

        private final Condition condition;

        public ConditionSignal(Lock lock, Condition condition) {
            this.lock = lock;
            this.condition = condition;
        }

        @Override
        public void run() {
            lock.lock();
            try {
                System.out.println("begin condition signal");
                condition.signal();
                System.out.println("end condition signal");
            } finally {
                lock.unlock();
            }
        }
    }

}
